/**
 * 人才库-加入/移出黑名单modal
 */
import React, { memo, useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Spin, Alert, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getEmployeeInfoList } from '@/services/components/userform';
import { onAddBlackList, onRemoveBlackList, getTalentApplyStatus } from '@/pages/Recruitment/TalentsManagement/service';
import { getDict } from '@/utils/dataDictUtil';
import styles from './index.less';

const FORM_DEFAULT_LAYOUT = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 15
    }
};
const { TextArea } = Input;
const { Option } = Select;

const RenderSelect = memo(({ dict, onChange, ...rest }) => (
    <Select
        placeholder="请选择"
        onChange={val => {
            onChange(val);
        }}
        {...rest}
    >
        {dict.map(item => (
            <Select.Option key={item.value} value={item.value}>
                {item.text}
            </Select.Option>
        ))}
    </Select>
));
const MoreOperateModal = ({
    form,
    talentCode,
    onOk,
    messageType,
    visible = false,
    operateType = 'add',
    defaultNoticeEmployee = [],
    resumeStep,
    ...rest
}) => {
    const { getFieldDecorator, validateFields, resetFields } = form;
    const [blacklistBlockType, setBlacklistBlockType] = useState([]);
    const [hintMessage, setHintMessage] = useState('');
    // 获取人员
    const { data: employeeList, loading: employeeLoading } = useRequest(
        () => {
            if (visible) {
                return getEmployeeInfoList({});
            }
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            manual: operateType === 'add',
            refreshDeps: [visible],
            initialData: [],
            ...defaultFormatResult
        }
    );

    // 获取当前人才所应聘岗位
    const { data: jobData, loading: jobLoading, run: jobRun } = useRequest(
        () => {
            if (visible) {
                return getTalentApplyStatus(talentCode);
            }
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            manual: !(operateType === 'add' && messageType === 1),
            refreshDeps: [visible],
            ...defaultFormatResult
        }
    );
    // 获取拉黑理由列表
    React.useEffect(() => {
        // 加入黑名单获取
        if (operateType === 'add') {
            getDict('blacklistBlockType').then(ret => setBlacklistBlockType(ret));
        }
    }, []);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const handleOk = () => {
        validateFields(async (err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            try {
                setSubmitLoading(true);
                const getHandler = () => {
                    if (operateType === 'add') {
                        return onAddBlackList({
                            blockDesc: values.blockDesc,
                            blockType: values.blockType,
                            blockStageId: resumeStep,
                            talentCode
                        });
                    }
                    return onRemoveBlackList({
                        talentCode,
                        reason: values.reason,
                        noticeEmployees: values?.noticeEmployees ?? []
                    });
                };
                const { code, msg } = await getHandler();
                if (code === 10000) {
                    message.success(operateType === 'add' ? '此简历已成功加入黑名单！' : '此简历已成功移出黑名单！');
                    onOk();
                } else {
                    message.error(msg);
                }
                setSubmitLoading(false);
            } catch (e) {
                setSubmitLoading(false);
                console.log(e, '黑名单操作失败！');
            }
        });
    };
    useEffect(() => {
        let messageInfo = '';
        if (operateType === 'add') {
            const jobs = (Array.isArray(jobData) ? jobData : []).map(item => item.dutyName).join('、');
            switch (messageType) {
                case 1:
                    messageInfo = `该候选人正在应聘${jobs}，拉黑后从应聘岗位中自动淘汰！`;
                    break;
                case 2:
                    messageInfo = '该简历已关联招聘需求，拉黑后简历自动淘汰！';
                    break;
                default:
            }
        } else {
            messageInfo = '恢复加入黑名单之前的阶段，状态为淘汰且支持推荐到其他岗位！';
        }
        if (messageInfo) setHintMessage(messageInfo);
    }, [messageType, jobData]);
    useEffect(() => {
        if (messageType === 1 && operateType === 'add') {
            jobRun();
        }
    }, [messageType]);
    useEffect(() => {
        if (visible && defaultNoticeEmployee.length && employeeList.length) {
            const noticeEmployees = defaultNoticeEmployee.filter(item =>
                employeeList.filter(e => e.employeeCode === item)
            );
            form.setFieldsValue({
                noticeEmployees
            });
        }
    }, [visible, employeeList.length]);
    return (
        <Modal
            {...rest}
            visible={visible}
            width={600}
            onOk={handleOk}
            confirmLoading={submitLoading}
            destroyOnClose
            afterClose={() => {
                resetFields();
            }}
            className={styles.modalWrap}
        >
            <Spin spinning={employeeLoading || jobLoading}>
                {hintMessage ? <Alert message={hintMessage} banner type="warning" /> : null}
                <Form {...FORM_DEFAULT_LAYOUT} className={styles.modalFormWrap}>
                    {operateType === 'add' ? (
                        <>
                            <Form.Item label="拉黑理由">
                                {getFieldDecorator('blockType', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '拉黑理由不能为空！'
                                        }
                                    ]
                                })(<RenderSelect dict={blacklistBlockType} />)}
                            </Form.Item>
                            <Form.Item label="描述">
                                {getFieldDecorator('blockDesc')(
                                    <TextArea
                                        placeholder="请输入理由！"
                                        autoSize={{ minRows: 3, maxRows: 6 }}
                                        maxLength={200}
                                    />
                                )}
                            </Form.Item>
                        </>
                    ) : (
                        <>
                            <Form.Item label="通知人员">
                                {getFieldDecorator(
                                    'noticeEmployees',
                                    {}
                                )(
                                    <Select
                                        mode="multiple"
                                        style={{ width: '100%' }}
                                        placeholder="请选择通知人员"
                                        allowClear
                                        optionFilterProp="children"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {employeeList?.map(item => (
                                            <Option value={item.employeeCode} key={item.employeeCode}>
                                                {item.employeeName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="理由">
                                {getFieldDecorator('reason', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '移出理由不能为空！'
                                        }
                                    ]
                                })(
                                    <TextArea
                                        placeholder="请输入理由"
                                        autoSize={{ minRows: 3, maxRows: 6 }}
                                        maxLength={200}
                                    />
                                )}
                            </Form.Item>
                        </>
                    )}
                </Form>
            </Spin>
        </Modal>
    );
};

export default Form.create()(MoreOperateModal);
